package com.ruitaowang.admin.view.api;

import com.alibaba.fastjson.JSON;
import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.core.domain.Company;
import com.ruitaowang.core.domain.SNSWXUserinfo;
import com.ruitaowang.core.domain.SysUser;
import com.ruitaowang.core.properties.ConfigProperties;
import com.ruitaowang.core.utils.TimeUtils;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.CompanyService;
import com.ruitaowang.goods.service.WXUserinfoService;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import tech.lingyi.wx.msg.out.TemplateData;
import tech.lingyi.wx.msg.out.TemplateItem;
import wx.wechat.api.MPAPI;
import wx.wechat.common.Configure;
import wx.wechat.common.RandomStringGenerator;
import wx.wechat.common.signature.Signature;
import wx.wechat.service.mp.MPService;
import wx.wechat.utils.XMLUtils;

import java.io.UnsupportedEncodingException;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by neal on 6/07/2017.
 */
@RestController
public class APIWeChatController extends BaseController {


    @Autowired
    private WXUserinfoService wxUserinfoService;
    @Autowired
    private CompanyService companyService;
    @Value("${host.api}")
    private String host;
    /**
     * @function 创建菜单
     */
    @RequestMapping(value = "/api/wx/menu/create", method = RequestMethod.POST)
    public String createMenu(String json) throws Exception {
        return this.renderJson(MsgOut.success(new MPService().createMenuForMP(json)));
    }

    /**
     * @function 获取菜单
     */
    @RequestMapping(value = "/api/wx/menu/list", method = RequestMethod.GET)
    public String getMenu() throws Exception {
        return this.renderJson(MsgOut.success(JSON.parse(new MPService().getMenuForMP())));
    }
    /**
     * @function 删除菜单
     */
    @RequestMapping(value = "/api/wx/menu/delete", method = RequestMethod.DELETE)
    public String deleteMenu() throws Exception {
        return this.renderJson(MsgOut.success(new MPService().deleteMenuForMP()));
    }

    /**
     * @function 发送模版消息
     */
    @RequestMapping(value = "/api/wx/message/template/send")
    public String sendTemplateMsg(String data) throws Exception {
        return this.renderJson(MsgOut.success(new MPService().getAPIEnter4TemplateMsg(data)));
    }


    /**
     * @function 接收微信公众号的消息
     */
    @RequestMapping(value = "/api/wx/events", method = RequestMethod.GET)
    public String valid(String signature, String timestamp, String nonce, String echostr) {
        MPAPI mpapi = new MPAPI();
        return mpapi.portal(signature, timestamp, nonce, echostr);
    }

    @RequestMapping(value = "/api/wx/jurisdiction", method = RequestMethod.GET)
    public Object jurisdiction() {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        String openid = wxUserinfoService.selectByPK(user.getId()).getOpenid();
        //获取随机字符串
        String nonceStr = RandomStringGenerator.getRandomStringByLength(20);

        //最终返回的结果
        Map<String, Object> result = new HashMap<>();

        //返回商户对应的AppID
        result.put("appId", Configure.appID);

        result.put("timeStamp", Instant.now().getEpochSecond());

        result.put("nonceStr", nonceStr);

        result.put("package", "user_id=" + openid);

        result.put("signType", "MD5");

        result.put("paySign", Signature.getSign4Pay(result));

        return result;
    }

    /**
     * 开发者模式, 负责进行消息处理
     * @param body xml
     * @return
     */
    @RequestMapping(value = "/api/wx/events", method = RequestMethod.POST)
    public String handle(@RequestBody String body) throws DocumentException, UnsupportedEncodingException {
        //将消息转化为Map
        Map<String, Object> messageMap = XMLUtils.XML2Map(body);
        String msgType = String.valueOf(messageMap.get("MsgType"));
        String toUserName = String.valueOf(messageMap.get("ToUserName"));
        String fromUserName = String.valueOf(messageMap.get("FromUserName"));
        Object mediaId = messageMap.get("MediaId");
        StringBuffer sb = new StringBuffer();
        if("event".equals(msgType)){//执行事件
            String eventType = String.valueOf(messageMap.get("Event"));

            switch (eventType) {
                case "subscribe"://关注
                    sb.append("<xml>");
                    sb.append("<ToUserName><![CDATA[").append(fromUserName).append("]]></ToUserName>");
                    sb.append("<FromUserName><![CDATA[").append(toUserName).append("]]></FromUserName>");
                    sb.append("<CreateTime>").append(new Date().getTime()).append("</CreateTime>");
                    sb.append("<MsgType><![CDATA[news]]></MsgType>");
                    sb.append("<ArticleCount>1</ArticleCount>");
                    sb.append("<Articles>");
                    sb.append("<item>");
                    sb.append("<Title><![CDATA[共享引流开创者]]></Title>");
                    sb.append("<Description><![CDATA[我们是工业和信息化部中小企业发展促进中心信息化公共服务平台中小企业法律咨询与服务平台指定的互联网服务机构！\n我们致力于为商家提供免费的注册运营服务！\n我们致力于让消费者永享低价高质购物体验！\n我们是一个有愿景、有使命、有情怀的团队，竭诚为您服务！\n更多详情请继续关注了解]]></Description>");
                    sb.append("<PicUrl><![CDATA[https://mmbiz.qpic.cn/mmbiz_jpg/caIGZqAEWgia4mxzVjOkbDPmVOR2oicSjoHA2mQggx1GybAYn6UOYs1I8VfdMSnvicCJEZ51YQGuDPDOu0ofPiandA/0?wx_fmt=jpeg]]></PicUrl>");
                    sb.append("<Url><![CDATA[https://mp.weixin.qq.com/s/EDPYc8zKg7AfY7hdny4arw]]></Url>");
                    sb.append("</item>");
                    sb.append("</Articles>");
                    sb.append("</xml>");
                    break;
                case "unsubscribe"://取消关注
                    //发送惋惜消息
                    break;
                case "SCAN"://扫描
                    break;
                case "LOCATION"://地址
                    break;
                case "CLICK"://点击事件
                    break;
                case "VIEW"://跳转
                    break;
                case "card_pass_check"://卡券审核通过
                    break;
                case "card_not_pass_check"://卡券审核失败
                    break;
                case "user_get_card"://用户领取卡券
                    break;
                case "user_del_card"://用户删除卡券
                    break;
                case "user_view_card"://用户浏览会员卡
                    break;
                case "user_consume_card"://用户核销卡券
                    break;
                case "merchant_order"://微小店用户下单付款
                    break;
                case "user_enter_tempsession"://小程序“客服会话按钮”进进入会话事件
                /*
                    <xml>
                        <ToUserName><![CDATA[toUser]]></ToUserName>
                        <FromUserName><![CDATA[fromUser]]></FromUserName>
                        <CreateTime>1482048670</CreateTime>
                        <MsgType><![CDATA[event]]></MsgType>
                        <Event><![CDATA[user_enter_tempsession]]></Event>
                        <SessionFrom><![CDATA[sessionFrom]]></SessionFrom>
                    </xml>
                */

                    sb.append("<xml>");
                    sb.append("<ToUserName><![CDATA[").append(fromUserName).append("]]></ToUserName>");
                    sb.append("<FromUserName><![CDATA[").append(toUserName).append("]]></FromUserName>");
                    sb.append("<CreateTime>").append(new Date().getTime()).append("</CreateTime>");
                    sb.append("<MsgType><![CDATA[transfer_customer_service]]></MsgType>");
//                    sb.append("<TransInfo><KfAccount><![CDATA[").append("ruitao001").append("]]></KfAccount></TransInfo>");
                    sb.append("</xml>");

                    break;
                default:
                    break;
            }
        } else {

            switch (msgType) {
                case"text":
                    String content = String.valueOf(messageMap.get("Content"));
                    if("联系客服".equals(content)){
                        sb.append("<xml>");
                        sb.append("<ToUserName><![CDATA[").append(fromUserName).append("]]></ToUserName>");
                        sb.append("<FromUserName><![CDATA[").append(toUserName).append("]]></FromUserName>");
                        sb.append("<CreateTime>").append(new Date().getTime()).append("</CreateTime>");
                        sb.append("<MsgType><![CDATA[transfer_customer_service]]></MsgType>");
                        sb.append("</xml>");
                    }

                    if("联系指定客服".equals(content)){
                        sb.append("<xml>");
                        sb.append("<ToUserName><![CDATA[").append(fromUserName).append("]]></ToUserName>");
                        sb.append("<FromUserName><![CDATA[").append(toUserName).append("]]></FromUserName>");
                        sb.append("<CreateTime>").append(new Date().getTime()).append("</CreateTime>");
                        sb.append("<MsgType><![CDATA[transfer_customer_service]]></MsgType>");
                        sb.append("<TransInfo><KfAccount><![CDATA[").append("ruitao001").append("]]></KfAccount></TransInfo>");
                        sb.append("</xml>");
                    }

                    sb.append("<xml>");
                    sb.append("<ToUserName><![CDATA[").append(fromUserName).append("]]></ToUserName>");
                    sb.append("<FromUserName><![CDATA[").append(toUserName).append("]]></FromUserName>");
                    sb.append("<Content><![CDATA[").append("回复\"联系客服\"，马上有专人为您服务。").append("]]></Content>");
                    sb.append("<CreateTime>").append(new Date().getTime()).append("</CreateTime>");
                    sb.append("<MsgType><![CDATA[text]]></MsgType>");
                    sb.append("</xml>");
                    break;
                case"image":
                    if(ObjectUtils.isEmpty(mediaId)){
                        break;
                    }
//                    sb.append("<xml>");
//                    sb.append("<ToUserName><![CDATA[").append(fromUserName).append("]]></ToUserName>");
//                    sb.append("<FromUserName><![CDATA[").append(toUserName).append("]]></FromUserName>");
//                    sb.append("<CreateTime>").append(new Date().getTime()).append("</CreateTime>");
//                    sb.append("<MsgType><![CDATA[").append(msgType).append("]]></MsgType>");
//                    sb.append("<Image>\n");
//                    sb.append("<MediaId><![CDATA[").append(String.valueOf(messageMap.get("MediaId"))).append("]]></MediaId>\n");
//                    sb.append("</Image>\n");
//                    sb.append("</xml>");
//                    InImageMsg inImageMsg = new InImageMsg(toUserName, fromUserName, (int) (new Date().getTime()), msgType);
//                    inImageMsg.setMediaId((String) mediaId);
//                    inImageMsg.setPicUrl(String.valueOf(messageMap.get("PicUrl")));
//                    redisTemplate.convertAndSend("weixinMsg", inImageMsg);
                    break;
                case"voice":
                    if(ObjectUtils.isEmpty(mediaId)){
                        break;
                    }
//                    sb.append("<xml>");
//                    sb.append("<ToUserName><![CDATA[").append(fromUserName).append("]]></ToUserName>");
//                    sb.append("<FromUserName><![CDATA[").append(toUserName).append("]]></FromUserName>");
//                    sb.append("<CreateTime>").append(new Date().getTime()).append("</CreateTime>");
//                    sb.append("<MsgType><![CDATA[").append(msgType).append("]]></MsgType>");
//                    sb.append("<Voice>\n");
//                    sb.append("<MediaId><![CDATA[").append(String.valueOf(messageMap.get("MediaId"))).append("]]></MediaId>\n");
//                    sb.append("</Voice>\n");
//                    sb.append("</xml>");
                    break;
                case"video":
                    if(ObjectUtils.isEmpty(mediaId)){
                        break;
                    }
//                    sb.append("<xml>");
//                    sb.append("<ToUserName><![CDATA[").append(fromUserName).append("]]></ToUserName>");
//                    sb.append("<FromUserName><![CDATA[").append(toUserName).append("]]></FromUserName>");
//                    sb.append("<CreateTime>").append(new Date().getTime()).append("</CreateTime>");
//                    sb.append("<MsgType><![CDATA[music]]></MsgType>");
//                    sb.append("<Music>\n");
//                    sb.append("<Title><![CDATA[").append("Stay Quirt").append("]]></Title>\n");
//                    sb.append("<Description><![CDATA[").append("singer: neal.").append("]]></Description>\n");
//                    sb.append("<MusicUrl><![CDATA[").append("http://m10.music.126.net/20170602151630/40ba5ca94756a57d148202efefb9cccb/ymusic/4f7a/a43f/945f/b18751a87bc766295fea4a63c4d3eb1b.mp3").append("]]></MusicUrl>\n");
//                    sb.append("<HQMusicUrl><![CDATA[").append("http://m10.music.126.net/20170602151630/40ba5ca94756a57d148202efefb9cccb/ymusic/4f7a/a43f/945f/b18751a87bc766295fea4a63c4d3eb1b.mp3").append("]]></HQMusicUrl>\n");
//                    sb.append("</Music>\n");
//                    sb.append("</xml>");
//                    InVideoMsg inVideoMsg = new InVideoMsg(toUserName, fromUserName, (int) (new Date().getTime()), msgType);
//                    inVideoMsg.setMediaId((String) mediaId);
//                    inVideoMsg.setThumbMediaId(String.valueOf(messageMap.get("ThumbMediaId")));
                    break;
                case"shortvideo":
                    break;
                case"location":
                    break;
                case"link":
                    break;
                case"music":
                    if(ObjectUtils.isEmpty(mediaId)){
                        break;
                    }
//                    sb.append("<xml>");
//                    sb.append("<ToUserName><![CDATA[").append(fromUserName).append("]]></ToUserName>");
//                    sb.append("<FromUserName><![CDATA[").append(toUserName).append("]]></FromUserName>");
//                    sb.append("<CreateTime>").append(new Date().getTime()).append("</CreateTime>");
//                    sb.append("<MsgType><![CDATA[").append(msgType).append("]]></MsgType>");
//                    sb.append("<Music>\n");
//                    sb.append("<Title><![CDATA[").append("Stay Quirt").append("]]></Title>\n");
//                    sb.append("<Description><![CDATA[").append("singer: neal.").append("]]></Description>\n");
//                    sb.append("<MusicUrl><![CDATA[").append("http://m10.music.126.net/20170602151630/40ba5ca94756a57d148202efefb9cccb/ymusic/4f7a/a43f/945f/b18751a87bc766295fea4a63c4d3eb1b.mp3").append("]]></MusicUrl>\n");
//                    sb.append("<HQMusicUrl><![CDATA[").append("http://m10.music.126.net/20170602151630/40ba5ca94756a57d148202efefb9cccb/ymusic/4f7a/a43f/945f/b18751a87bc766295fea4a63c4d3eb1b.mp3").append("]]></HQMusicUrl>\n");
//                    sb.append("</Music>\n");
//                    sb.append("</xml>");
                    break;
                default:
                    break;
            }
        }
        return sb.toString();
    }

    /**
     * @function 一次性消息订阅
     */
    @RequestMapping(value = "/api/wx/subscribemsg", method = RequestMethod.GET)
    public String subscribemsg(String url) throws Exception {
        return this.renderJson(MsgOut.success(new MPService().subscribemsg(url)));
    }

    /**
     * @function 一次性消息订阅, 重定向处理
     */
    @RequestMapping(value = "/api/wx/redirecturl", method = RequestMethod.GET)
    public String subRedirectUrlHandler(String openid, String template_id, String action, String scene, String reserved) throws Exception {
        LOGGER.info("{}, {}, {}, {}", openid, template_id, action, scene, reserved);

        TemplateData templateData = TemplateData.New();
        SNSWXUserinfo snswxUserinfo = wxUserinfoService.selectByOpenId(openid);
        if(ObjectUtils.isEmpty(snswxUserinfo)){
            return this.renderJson(MsgOut.error());
        }
        templateData.setTouser(snswxUserinfo.getOpenid());
        templateData.setTemplate_id(template_id);
        templateData.setUrl("http://www.ruitaowang.com");
        templateData.setScene(scene);
        templateData.setTitle("title");
        templateData.setData(new TemplateItem());
        templateData.add("content", "你好", "#173177");
        LOGGER.info("TemplateMsg: {}", templateData.build());
        return this.renderJson(MsgOut.success(new MPService().getAPIEnter4subscribemsg(templateData)));
    }
}
